# coding: utf-8

# -------------------------------------------------------------------------------
# Name:         email.py
# Description:
# Author:       XiangjunZhao
# EMAIL:        2419352654@qq.com
# Date:         2020/10/27 10:06
# -------------------------------------------------------------------------------
import json
import threading
from django.conf import settings
from django.core.mail.backends.smtp import EmailBackend

from apps.SystemService.models import Parameter

__all__ = ['CustomEmailBackend']


class CustomEmailBackend(EmailBackend):
    """
    A wrapper that manages the SMTP network connection.
    """

    def __init__(self, host=None, port=None, username=None, password=None,
                 use_tls=None, fail_silently=False, use_ssl=None, timeout=None,
                 ssl_keyfile=None, ssl_certfile=None,
                 **kwargs):
        super().__init__(fail_silently=fail_silently)

        parameter = Parameter.objects.filter(key='EMAIL', is_deleted=False).first()
        if parameter:
            value = json.loads(parameter.value)
            if value:
                host = host or value.get('EMAIL_HOST')
                port = port or value.get('EMAIL_PORT')
                username = username or value.get('EMAIL_HOST_USER')
                password = password or value.get('EMAIL_HOST_PASSWORD')
                use_ssl = use_ssl or value.get('EMAIL_USE_SSL')

        self.host = host or settings.EMAIL_HOST
        self.port = port or settings.EMAIL_PORT
        self.username = settings.EMAIL_HOST_USER if username is None else username
        self.password = settings.EMAIL_HOST_PASSWORD if password is None else password
        self.use_tls = settings.EMAIL_USE_TLS if use_tls is None else use_tls
        self.use_ssl = settings.EMAIL_USE_SSL if use_ssl is None else use_ssl
        self.timeout = settings.EMAIL_TIMEOUT if timeout is None else timeout
        self.ssl_keyfile = settings.EMAIL_SSL_KEYFILE if ssl_keyfile is None else ssl_keyfile
        self.ssl_certfile = settings.EMAIL_SSL_CERTFILE if ssl_certfile is None else ssl_certfile
        if self.use_ssl and self.use_tls:
            raise ValueError(
                "EMAIL_USE_TLS/EMAIL_USE_SSL are mutually exclusive, so only set "
                "one of those settings to True.")
        self.connection = None
        self._lock = threading.RLock()
